/*
 * @Author: Choisaaaa
 * @Date: 2018/5/3  16:04
 * 商品列表模块
 */

import React from "react";
import {Link} from "react-router-dom";

import "./product-list.scss";
import Footer from "component/footer/footer.jsx"
import PageTitle from 'component/page-title/page-title.jsx';
import Pagination from 'util/pagination/pagination.jsx';
import TableList from 'util/table-list/table-list.jsx';
import ListSearch from 'page/product/product/product-list-search.jsx';
import MUtil from 'util/mm.jsx'
import Product from 'service/product-service.jsx'

const _mm = new MUtil();
const _product = new Product();

class ProductList extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            pageNum : 1,        //当前的页数
            list : [],          //这里需要定义list为数据，否则后面无法使用map函数
            listType : "list"   //查找的类型默认设置为按照列表查询
        };
    }
    componentDidMount(){
        this.loadProductList();
    }
    loadProductList() {//加载商品列表
        let listParam = {};
        listParam.listType = this.state.listType;
        listParam.pageNum = this.state.pageNum;
        if(this.state.listType === "search"){ //如果是按搜索分页显示
            listParam.searchType = this.state.searchType;
            listParam.keyword = this.state.searchKeyWord;
            if(this.state.searchType == "productId"){
                var reg = new RegExp("^[0-9]*$");
                if (!reg.test($.trim(this.state.searchKeyWord))) {
                    _mm.errorTips("输入的商品ID格式不正确，订单号只由数字组成")
                    return ;
                }
            }
        }
        _product.getProductList(listParam).then(res =>{
            this.setState(res);
        },err => {
            this.setState({
                list: []
            });
            _mm.errorTips(err)
        });

    }
    onPageNumChange(pageNum){//更新页数
        this.setState({
            pageNum : pageNum
        },() => {
            this.loadProductList();//重新渲染
        });
    }
    onSetProductStatus(e,productId){//商品下架
        let currentStatus = parseInt(e.target.value);
        let newStatus ;
        let confirmTips = "";
        let flag =  true;
        if(currentStatus === -1){
            //todo
            //管理员不允许强行上架商品
            _mm.errorTips("管理员不允许强行上架商品!该功能已经取消")
            return;

            confirmTips = "确定要上架该商品吗？";
            newStatus = 2;
            if( !window.confirm(confirmTips)){
                flag =  false;
            }

        }else if(currentStatus === 0){
            confirmTips = "再次审核中：商品是否能够售卖？通过点【确定】 不通过点【取消】";
           if( window.confirm(confirmTips)){
               newStatus = 2;
           }else{
               newStatus = 0;
           }
        }else if(currentStatus === 1) {
            confirmTips = "审核中：该商品是否能够售卖？通过点确定 不通过点取消";
            if( window.confirm(confirmTips)){
                newStatus = 2;
            }else{
                newStatus = 0;
            }
        }else if(currentStatus === 2) {
            confirmTips = "确认要下架该商品吗？";
            newStatus = -1;
            if(!window.confirm(confirmTips)){
                flag =  false;
            }
        }
        if(flag){
            _product.setProductStatus({
                productId : productId,
                status : newStatus
            }).then( res =>{
                _mm.successTips(res);
                this.loadProductList();//重新渲染
            },err => {
                _mm.errorTips(err);
            });
        }
    }

    onSearch(searchType, searchKeyword){  // 搜索按钮的事件
        let listType = searchKeyword === '' ? 'list' : 'search';
        this.setState({
            listType        : listType,
            pageNum         : 1,
            searchType      : searchType,
            searchKeyWord   : searchKeyword
        }, () => {
            this.loadProductList();
        });
    }
    render(){
        let tableHeader = [
            {name : "商品ID" ,width : "8%"},
            {name : "卖家" ,width : "8%"},
            {name : "商品信息" ,width : "30%"},
            {name : "原价" ,width : "7%"},
            {name : "售价" ,width : "7%"},
            {name : "发布时间" ,width : "15%"},
            {name : "状态" ,width : "10%"},
            {name : "操作" ,width : "15%"},
        ];
        let ListBody = this.state.list.map((product,index) =>{
            let buttonHtml ;
            let productStatus;
            if(`${product.enableStatus}`== -1){
                productStatus = "已下架"
                buttonHtml = (<button className="btn btn-xs btn-success" value="-1"
                                  onClick={(e) => {this.onSetProductStatus(e, product.id, product.status)}}>去上架</button>);
            }else if(`${product.enableStatus}`== 0){
                productStatus = "不合格"
                buttonHtml = (<button className="btn btn-xs btn-info" value="0"
                                  onClick={(e) => {this.onSetProductStatus(e, product.id, product.status)}}>重新审核</button>);
            }else if(`${product.enableStatus}`== 1){
                productStatus = "待审核"
                buttonHtml = (<button className="btn btn-xs btn-primary" value="1"
                                  onClick={(e) => {this.onSetProductStatus(e, product.id, product.status)}}>去审核</button>);
            }else if(`${product.enableStatus}`== 2){
                productStatus = "已上架"
                buttonHtml = (<button className="btn btn-xs btn-danger" value="2"
                                      onClick={(e) => {this.onSetProductStatus(e, product.id, product.status)}}>去下架</button>);
            }
            return(
                <tr key={index}>
                    <td>{product.id}</td>
                    <td>{product.ownerName}</td>
                    <td>
                        <p>{product.productName}</p>
                        <p>{product.productSubtitle}</p>
                    </td>
                    <td>￥{product.normalPrice}</td>
                    <td>￥{product.promotionPrice}</td>
                    <td>{product.createTime}</td>
                    <td className="pro-status">
                        <p>{productStatus}</p>
                        {buttonHtml}
                    </td>
                    <td>
                        <Link className="opear" to={ `/product/detail/${product.id}`}>详情</Link>
                        <Link className="opear" to={  `/product/save/${product.id}`}>编辑</Link>
                    </td>
                </tr>
            )
        });
        return (
            <div id="page-wrapper">
                <PageTitle title="商品列表">
                <div className="page-header-right">
                    <Link  to="/product/save" className="btn btn-primary btn-lg">
                        <i className="fa fa-plus"/>
                        <span> 添加商品</span>
                    </Link>
                </div>
                </PageTitle>
                <ListSearch onSearch = {(searchType, searchKeyword) => {this.onSearch(searchType, searchKeyword)}}/>
                {
                    this.state.listType === "list"
                        ?(<div className="total-product">
                            <h3> 商品总数为:{this.state.total} (件)</h3>
                         </div>)
                        :(<div className="total-product">
                             <h3> 为你找到商品:{this.state.total} (件)</h3>
                         </div>)
                }


                <TableList tableHeads={tableHeader}>
                    {ListBody}
                </TableList>
                <Pagination current={this.state.pageNum}
                            total={this.state.total}
                            onChange={(pageNum) => this.onPageNumChange(pageNum)}/>
                <Footer/>
            </div>
        );
    }
}

export default ProductList;
